<?php
// 活动
class ActivityAction extends UserAction {
	//魔术方法
public function __construct(){
		parent::__construct();
	}
  //活动   hkj 2015年11月17日
  public function index(){
    $this->binding_mobile='11';
     $article_id= I('article_id') ; //
     $o_where['member_id']=$this->uid;
     $o_where['article_id']=$article_id;
     $where['article_id']=$article_id;
     $p=I('p');
     $activityModel=D('Activity');
   
//        if($list){  //如果已经领取,跳转到二维码页面
//            redirect(U)
//        }
//      var_dump($where);
      $list= $activityModel->getActivityReceiveList($where,$p,'add_time desc',6);  //获取领取记录列表
      $field='member_card,mobile,member_logo';
      foreach($list as $k=>$v){
          $m_where['id']=$v['member_id'];
          $member_msg=M('member')->field($field)->where($m_where)->find();
          $list[$k]['member_card']=$member_msg['member_card'];
          $list[$k]['member_logo']=$member_msg['member_logo'];
          $list[$k]['date']=date('Y年m月d日 H:i:s',$v['add_time']);
          $str1 = substr($member_msg['mobile'], 0, 4);
          $str2 = substr($member_msg['mobile'], 8);
          $list[$k]['member_mobile'] = $str1.'****'.$str2;
      }
      $this->count=$count=M('activity_receive')->where($where)->count();
//      var_dump($count);die;
      if(IS_AJAX){
          echo json_encode($list);die;
      }
      $this->list=$list;
       $getArticleShareLog=$activityModel->getArticleShareLog($o_where);
        //没有分享 不能领取
      if(empty($getArticleShareLog)){
        redirect(U("wap/usernotice/tweet_detail",array('id'=>$article_id)));
        exit();
      }
     $is_get=$activityModel->getActivityReceiveOne($o_where); //判断是否领取过
     $this->is_get=$is_get;
//      var_dump($list);die;
      $pre=C('DB_PREFIX');  //表前缀
      //获取商品信息
      $goods_msg=M()->table($pre.'article_tweet art')
          ->field('art.img,art.title,art.goods_num,g.goods_id,g.goods_name,g.goods_brief,g.shop_price,g.goods_img')
          ->where(array('art.id'=>$article_id))
          ->join($pre.'g_goods g on art.goods_id=g.goods_id')
          ->find();
      $goods_img=M('g_goods_gallery')->field('img_url')
          ->where(array('goods_id'=> $goods_msg['goods_id']))  //
          ->limit('2')
          ->select();
      $goods_msg['img_url']=$goods_img;
      $this->goods=$goods_msg;
//      var_dump($goods_msg);die;
    $now_address=M('g_user_draw_address')->where(array('user_id'=>$this->uid))->find();//获取当前用户收货地址
//      var_dump($now_address);die;
      $this->address=$now_address;
     //$this->bind_mobile=$_SESSION['member']['mobile'];
      $this->bind_mobile='11';//不显示绑定手机  可以不绑定的手机
      //微信分享
      $this->shar_url = $url = "http://".$_SERVER['HTTP_HOST'] . U('wap/Usernotice/tweet_detail',array('id' => $article_id, 'share' => $this->member_card));//分享地址
      $this->shar_title = $goods_msg['title'];///分享标题
      $this->shar_desc = $goods_msg['title'];///分享内容
      $this->shar_imgurl = "http://".$_SERVER['HTTP_HOST'].$goods_msg['img'];///分享图片地址
//    var_dump($now_address);
      $this->display();
  }
  //活动 领取记录  hkj 2015年11月17日
  public function activity_receive(){
     $article_id=$_REQUEST['article_id'];
     $article_id=I('article_id');
     var_dump($article_id);
     $where['article_id']=$article_id;
     $where['member_id']=$this->uid;
     $activityModel=D('Activity');
     $one=$activityModel->getActivityReceiveOne($where);
     var_dump($one);
  }
    //活动 分享记录  hkj 2015年11月17日
  public function activity_share(){
     $article_id=I('article_id');
     $where['article_id']=$article_id;
     $where['member_id']=$this->uid;
     $activityModel=D('Activity');
     $one=$activityModel->getArticleShareLog($where);
     $this->display();
  }
    //活动 分享记录新增  hkj 2015年11月17日
  public function set_activity_share(){
     $return_data['status']=0;
     $article_id=I('article_id');
     if(empty($article_id)){
       $return_data['error']="活动信息错误";
       echo json_encode($return_data);die;
     }
     $where['article_id']=$article_id;
     $where['member_id']=$this->uid;
     $activityModel=D('Activity');
     $one=$activityModel->setArticleShareLog($where);
     if($one!==false){
        M('article_tweet')->where(array('id'=>$article_id))->setInc('share_num');
       $return_data['status']=1;
       echo json_encode($return_data);die;
     }else{
      $return_data['error']="记录分享失败";
       echo json_encode($return_data);die;
     }
  }
 
  // 参与活动 领取产品
  public function activity_binding(){
     $return_data['status']=0;
      //不显示绑定手机  可以不绑定的手机
     $mb=$_SESSION['member']['mobile'];
      if(empty($mb)){
        $mb='11';
      }
     if(empty($mb)){
       $_POST['mobile']=$_POST['binding_mobile'];
       $mobile= $_POST['mobile'];
        if(empty($mobile)){
          $return_data['error']="请填写手机号";
          echo json_encode($return_data);die;
         }
         if(!check_phone($mobile)){
            $return_data['error']="手机号格式错误";
            echo json_encode($return_data);die;
         }
         $this->binding();
         $this->set_activity();
      }else{
        if(empty($_POST['mobile'])){
         // $_POST['mobile']=$_SESSION['member']['mobile'];
        }
         $mobile= $_POST['mobile'];
        if(empty($mobile)){
          $return_data['error']="请填写手机号";
          echo json_encode($return_data);die;
         }
         if(!check_phone($mobile)){
            $return_data['error']="手机号格式错误";
            echo json_encode($return_data);die;
         }
         $this->set_activity();
      } 
  
  } 
  // 参与活动 领取产品
  public function set_activity(){
      $return_data['status']=0;
      $article_id=I('article_id');
      //没有绑定手机 不能领取
        //不显示绑定手机  可以不绑定的手机
     $mb=$_SESSION['member']['mobile'];
      if(empty($mb)){
        $mb='11';
      }
     if(empty($mb)){
      $return_data['error']="请完善资料";
      echo json_encode($return_data);die;
      }
      $consignee=I('consignee');
      $address=I('address');
      $mobile=I('mobile');
      if(empty($consignee)){
        $return_data['error']="请填写收货人";
        echo json_encode($return_data);die;
      }
       if(empty($address)){
        $return_data['error']="请填写收货地址";
        echo json_encode($return_data);die;
      }
      if(empty($mobile)){
        $return_data['error']="请填写手机号码";
        echo json_encode($return_data);die;
      }
       //查询活动
      $field="tweet.*,goods.goods_name";
      $db_pre=C('DB_PREFIX');
      $article=M()->table($db_pre.'article_tweet tweet')//
      ->join($db_pre.'g_goods goods on goods.goods_id=tweet.goods_id')//
      ->where(array('tweet.id'=>$article_id))
      ->field($field)->find();//
        //活动不存在 不能领取
      if(empty($article)){
        $return_data['error']="活动不存在";
        echo json_encode($return_data);die;
      }
       if(empty($article['goods_id']) || empty($article['goods_name'])){
        $return_data['error']="活动产品不存在";
        echo json_encode($return_data);die;
      }
       if(empty($article['goods_num'])){
        $return_data['error']="活动奖品已领完";
        echo json_encode($return_data);die;
      }
      
      //查询是否已经参加活动
      $where=array();
      $where['article_id']=$article_id;
      $where['member_id']=$this->uid;
      $activityModel=D('Activity');
      
      $getArticleShareLog=$activityModel->getArticleShareLog($where);
        //没有分享 不能领取
      if(empty($getArticleShareLog)){
        $return_data['error']="没有分享到朋友圈不能领取";
        echo json_encode($return_data);die;
      }

      $activityReceive=$activityModel->getActivityReceiveOne($where); 
       //没有绑定手机 不能领取
      if($activityReceive){
        $return_data['error']="已经领取过产品";
        echo json_encode($return_data);die;
      }
//      //收货地址
//      $address=M('g_user_draw_address')->where(array('user_id'=>$this->uid))->find();
//      if(empty($address)){
//        $return_data['error']="请设置收货地址";
//        echo json_encode($return_data);die;
//      }
      //$article
        $add_data=array();
        $add_data['member_id']=$this->uid;
        $add_data['article_id']=$article['id'];
        $add_data['goods_id']=$article['goods_id'];
        $add_data['goods_name']=$article['goods_name'];

//        $add_data['address_name']=$address['address_name'];
        $add_data['consignee']=I('consignee');
//        $add_data['email']=$address['email'];
        $add_data['address']=I('address');
//        $add_data['zipcode']=$address['zipcode'];
//        $add_data['tel']=['tel'];
        $add_data['mobile']=I('mobile');
//        $add_data['sign_building']=$address['sign_building'];
//        $add_data['best_time']=$address['best_time'];
        $add_data['add_time']=time();
        $activity_receive_model=M('activity_receive');
        $article_tweet_model=M('article_tweet');

        $activity_receive_model->startTrans();
        $article_tweet_model->startTrans();

        $article_tweet_res=$article_tweet_model->where(array('id'=>$article_id))->setDec('goods_num');
        $activity_receive_res=$activity_receive_model->add($add_data);
        if($article_tweet_res!==false && $activity_receive_res!==false){
          $return_data['status']=1;
           $activity_receive_model->commit();
           $article_tweet_model->commit();
           $now_address=M('g_user_draw_address')->where(array('user_id'=>$this->uid))->find();//获取当前用户收货地址
           if(empty($now_address)){
             $address_data=array();
             $address_data['user_id']=$this->uid;
             $address_data['consignee']=$add_data['consignee'];
             $address_data['address']=$add_data['address'];
             $address_data['mobile']=$add_data['mobile'];
             M('g_user_draw_address')->add($address_data);
           }
          echo json_encode($return_data);die;
        }else{

           $activity_receive_model->rollback();
           $article_tweet_model->rollback();
           $return_data['error']="领取失败";
           echo json_encode($return_data);die;
        }
  }
  
  

    //验证是否绑定
    public function get_check_binding()
    {
        $return_data['status'] = 0;
        echo json_encode($return_data);
        die;
//        $user_agent = $user_agent = $_SERVER['HTTP_USER_AGENT'];
//        if (strpos($user_agent, 'MicroMessenger') === false) {
//            //不是微信浏览器
//            echo json_encode($return_data);
//            die;
//        }
        if (empty($this->uid)) {
            //未登录
            echo json_encode($return_data);
            die;
        }
        if (!empty($_SESSION['member']['mobile'])) {
            //已绑定
            echo json_encode($return_data);
            die;
        }
//        $is_check = $_REQUEST['binding_is_check'];// 重复再次弹出 1是 0否
//        //今天第一次显示 今天已经抽了不显示
//        $page = $_REQUEST['binding_page'];//绑定验证页面
//        if ($page) {
//            $page = 'check_binding_' . $page;
//            if (empty($is_check)) {// 重复不再次弹出
//                $show = $this->set_cookie_show($page);
//                if ($show) {
//                    $return_data['status'] = 0;
//                } else {
//                    $return_data['status'] = 1;
//                }
//                echo json_encode($return_data);
//                die;
//            }
//            $this->set_cookie_show($page);
//        }
        $return_data['status'] = 1;
        echo json_encode($return_data);
        die;
    }

    public function binding_send_sms()
    {

        $data['status'] = 0;
//        $user_agent = $_SERVER['HTTP_USER_AGENT'];
//        if (strpos($user_agent, 'MicroMessenger') === false) {
//            $data['msg'] = "请在微信内打开";
//            // echo json_encode($data);die;///--------------------------
//        }
        $send = $_SESSION['send'];
        $time = time();
        $s_time = $time - $send['add_time'];
        if ($s_time < 60) {
            $data['msg'] = "短信发送太频繁，请前后间隔60秒";
            echo json_encode($data);
            die;
        }
        $mobile = $_REQUEST['mobile'];
        if (empty($mobile) || check_phone($mobile) === false) {
            $data['msg'] = "手机号码错误";
            echo json_encode($data);
            die;
        }
        $code = rand(100000, 999999);
        $mseeage = "您的短信验证码为：{$code}。";
        //$res=//发送短信
        $send = $this->sendSMS($mobile, $mseeage);
        $send_status = 0;
        if ($send['status'] == 1) {
            $send_status = 1;
            //发送成功
            $data['status'] = 1;
            $data['msg'] = "短信发送成功";
            //$data['code']=$code;
            //存入session
            $s_data['mobile'] = $mobile;
            $s_data['add_time'] = $time;
            $s_data['code'] = $code;
            $_SESSION['send'] = $s_data;
        }else{
            $data['msg']=$send['error'];
            echo json_encode($data);die;
        }

        //存入数据库
        /* $send_data=$s_data;
         $send_data['message']=$message;
         $send_data['status']=1;
         M("send_log")->add($send_data);*/
        echo json_encode($data);
        die;
    }

    //绑定
    public function binding()
    {
        $data['status'] = 0;
        $code = $_SESSION['share'];
        $mem_password = $_POST['binding_mem_password'];
        $rep_password = $_POST['binding_rep_password'];
        $mobile = $_POST['binding_mobile'];
        $address=$_POST['address'];
        $consignee=$_POST['consignee'];
        //检测 手机验证码
        $_REQUEST['mobile'] = $mobile;
        $_REQUEST['mobile_code'] = $_POST['binding_mobile_code'];
        $send_return = $this->check_send_return();
        if ($send_return['error']) {
            $data['error'] = $send_return['error'];
            echo json_encode($data);
            die;
        }
        $openid = session('user_open_id');
        $member_info_now = M("member")->where(array('openid' => $openid))->find();
        if (empty($member_info_now)) {
            $data['error'] = '用户信息错误';
            echo json_encode($data);
            die;
        }
        if($code==$member_info_now['member_card']){
            $code="";
        }
        //绑定  手机号 已注册
        $where = array('mobile' => $mobile);
        $member_info_mobile = M("member")->where($where)->find();
        if ($member_info_mobile) {
            if ($member_info_mobile['id'] == $member_info_now['id']) {
                $data['status'] = 1;
                return true;
            }
            if ($member_info_mobile['openid']) {
                $data['error'] = "该手机号已被绑定";
                echo json_encode($data);
                die;
            }
            $openid = session('user_open_id');
            ///绑定
            $member_model = M("member");
            $member_model->startTrans();//开起事务
            $res2 = $member_model->where(array('openid' => $openid))->save(array('openid' => ''));
            $res1 = $member_model->where(array('mobile' => $mobile))->save(array('openid' => $openid));
            if ($res1 !== false && $res2 !== false) {
                //数据转移
                $member_model->commit();//提交事务
                //
                $now_uid = $member_info_now['id'];
                $set_uid = $member_info_mobile['id'];
                M('g_cart')->where(array('user_id' => $now_uid))->save(array('user_id' => $set_uid));
                M('bank_account')->where(array('member_id' => $now_uid))->save(array('member_id' => $set_uid));
                //M('member_rember_token')->where(array('member_id'=>$now_uid))->save(array('member_id'=>$set_uid));
                M('g_user_address')->where(array('user_id' => $now_uid))->save(array('user_id' => $set_uid));

                //记录session信息
                $user_data = array();
                $user_data['uid'] = $member_info_mobile['id'];
                $user_data['member_card'] = $member_info_mobile['member_card'];
                $user_data['member_name'] = $member_info_mobile['member_name'];
                $user_data['mobile'] = $member_info_mobile['mobile'];
                $_SESSION['member'] = $user_data;

                $data['status'] = 1;
                return true;
            } else {
                $member_model->rollback();//提交事务
                $data['error'] = "绑定失败";
                echo json_encode($data);
                die;
            }
        }
        //注册

        //注册验证 密码 是否为空 两次密码是否一致

        if (empty($mem_password)) {
            $data['error'] = "密码不能为空";
            echo json_encode($data);
            die;
        }
        if (empty($rep_password)) {
            $data['error'] = "重复密码不能为空";
            echo json_encode($data);
            die;
        }
        if ($rep_password != $mem_password) {
            $data['error'] = "两次密码不一致";
            echo json_encode($data);
            die;
        }
        ///手机 是否被注册
        if (empty($mobile)) {
            $data['error'] = "手机号码不存在";
            return $data;
        }
        $count = M("member")->where(array('mobile' => $mobile))->count();
        if ($count) {
            $data['error'] = "手机号码已被绑定";
            return $data;
        }
        if (!empty($code)) {
            $data_code = $this->getMemberCode($code);
            if (!empty($data_code)) {
                $m_data['recommend_code'] = $data_code['recommend_code'];//推荐码 (推荐人的推荐码 )
                $m_data['indirect_recommend_code'] = $data_code['indirect_recommend_code'];//间接推荐人推荐码 (推荐人的推荐人的推荐码 )
                $m_data['indirect2_recommend_code'] = $data_code['indirect2_recommend_code'];//间接2层推荐人推荐码 (推荐人的推荐人的推荐码 )
            }
        } else {
            $code = '01';
            $data_code = $this->getMemberCode($code);
            if (!empty($data_code)) {
                $m_data['recommend_code'] = $data_code['recommend_code'];//推荐码 (推荐人的推荐码 )
                $m_data['indirect_recommend_code'] = $data_code['indirect_recommend_code'];//间接推荐人推荐码 (推荐人的推荐人的推荐码 )
                $m_data['indirect2_recommend_code'] = $data_code['indirect2_recommend_code'];//间接2层推荐人推荐码 (推荐人的推荐人的推荐码 )
            }
        }
        //注册
        $m_data['mobile'] = $mobile;
        if (empty($member_info_now['member_name'])) {
            $m_data['member_name'] = 'FG' . substr($mobile, 0, -4);
        }
        $m_data['password'] = md5($mem_password);
        //$openid=session('user_open_id');
        // $m_data['openid']=$openid;
        ///绑定赠送 用户金额Register give money
        $register_give_money = M('sys_param')->where(array('param_code' => 'register_give_money'))->getField('param_value');//返利比例；
        if ($register_give_money > 0) {
            ///随机5到XX
            $register_give_money = $this->set_register_give_money($register_give_money);
            $m_data_detail['balance_give'] = $register_give_money;//用户扩展表赠送金额 注册赠送20块钱  米值
        } else {
            $m_data_detail['balance_give'] = 0;//用户扩展表 注册赠送20块钱  米值
        }

        $m_data_detail['points'] = 10;//用户扩展表 注册赠送10积分

        $member_model = M('member');
        $member_detail_model = M('member_detail');

        $member_model->startTrans();//开起事务
        $member_detail_model->startTrans();//开起事务

        $add = $member_model->where(array('id' => $_SESSION["member"]['uid']))->save($m_data);

        $member_detail_add = $member_detail_model->where(array('member_id' => $_SESSION["member"]['uid']))->save($m_data_detail);

        if ($add !== false && $member_detail_add !== false) {

            //绑定成功
            $data['status'] = 1;
            //记录session信息
            $user_data = array();
            $user_data['uid'] = $_SESSION["member"]['uid'];
            $user_data['member_card'] = $_SESSION["member"]['member_card'];
            if (!empty($m_data['member_name'])) {
                $user_data['member_name'] = $m_data['member_name'];
            } else {
                $user_data['member_name'] = $_SESSION['member']['member_name'];
            }
            $user_data['member_name'] = $m_data['member_name'];
            $user_data['mobile'] = $m_data['mobile'];
            $_SESSION['member'] = $user_data;
            //登录日志 记录
            //$this->set_member_login_log();

            $member_model->commit();//提交事务
            $member_detail_model->commit();//提交事务
            if ($m_data_detail['balance_give'] > 0) {
                ///记录消费日志
                $log_data['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
                $log_data['member_id'] = $_SESSION["member"]['uid'];
                $log_data['money'] = $m_data_detail['balance_give'];
                $log_data['status'] = 1;//状态 1收入 2支出
                $log_data['des'] = "绑定手机赠送￥" . $log_data['money'];//消费介绍
                $log_data['add_time'] = time();//消费时间
                $this->set_member_consume_record($log_data);
            }
            //注册赠送10积分
            if ($m_data_detail['points'] > 0) {
                ///记录日志
                $log_integral_data['type'] = 1;//消费类型 1获得 2消费
                $log_integral_data['member_id'] = $_SESSION["member"]['uid'];
                $log_integral_data['integral'] = $m_data_detail['points'];
                $log_integral_data['status'] = 1;//状态 1收入 2支出
                $log_integral_data['des'] = "绑定手机赠送+" . $m_data_detail['points'];//消费介绍
                $log_integral_data['add_time'] = time();//消费时间
                $this->set_member_integral($log_integral_data);
            }
            return true;
        } else {
            $member_model->rollback();//回滚事务
            $member_detail_model->rollback();//回滚事务
            $data['error'] = "系统错误请稍候再试";
            echo json_encode($data); die;
        }
    
    }
}